/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.liquidByte.trafficMustang.server.webService.base;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;

/**
 * Conjunto de implementações bases pertinentes ao 
 * funcionamento de um web service restful de acordo
 * com as especificidades do projeto
 * @author Alexandre
 */
public abstract class WebService {
    private Gson gson;
    
    private Gson getGson() {
        if (this.gson == null) {
            this.gson = new Gson();
        }
        return this.gson;
    }
    
    protected <T> T toObject(String data, Class<T> targetClass) throws JsonParseException {
        return this.getGson().fromJson(data, targetClass);
    }
    protected String result(Object data) {
        if (data == null) {
            return this.success();
        }
        else if (data instanceof Exception) {
            return this.error((Exception)data);
        } else {
            ResultMessage dto = ResultMessage.success(this.getGson().toJson(data));
            return this.getGson().toJson(dto);
        }
    }
    protected String error(Exception ex) {
        ResultMessage dto = ResultMessage.fromException(ex);
        return this.getGson().toJson(dto);
    }
    protected String success() {
        return this.getGson().toJson(ResultMessage.success());
    }
}
